package List;

public class SeqList<T> implements IList<T> {
    // 一维数组: 存储数据元素
    private Object[] elements;

    // 元素个数
    private int length;

    // 最大容量
    private int maxLength;

    public SeqList() {
        this(4);
    }

    public SeqList(int maxLength) {
        this.length = 0;
        this.maxLength = maxLength;
        this.elements = new Object[this.maxLength];
    }

    @Override
    public T get(int i) throws Exception {
        // 判定下标i是否合法
        if (i < 0 || i >= this.length) {
            throw new ArrayIndexOutOfBoundsException(i);
        }
        // 返回下标位置元素
        return (T) this.elements[i];
    }

    @Override
    public void insert(T x) throws Exception {
        // 判定线性表是否装满
        if (this.length == this.maxLength) {
            throw new Exception("顺序表已装满!");
        }
        // 在线性表尾部新增元素
        this.elements[this.length] = x;
        this.length++;
    }

    @Override
    public void insert(int i, T x) throws Exception {
        // 判定是否有剩余空间
        if (this.length == this.maxLength) {
            throw new Exception("顺序表已装满!");
        }
        // 判定下标i是否合法
        if (i < 0 || i > this.length) {
            throw new ArrayIndexOutOfBoundsException(i);
        }
        int index = this.length;
        for (; index > i; index--) {
            this.elements[index] = this.elements[index - 1];
        }
        this.elements[i] = x;
        this.length++;
    }

    @Override
    public T remove(int i) throws Exception {
        // 判定下标值是否合法
        if (i < 0 || i >= this.length) {
            throw new ArrayIndexOutOfBoundsException(i);
        }
        int index = i;
        // 保存被删除位置的元素
        Object t = this.elements[i];
        // 用下一个元素覆盖
        for (; index < this.length - 1; index++) {
            this.elements[index] = this.elements[index + 1];
        }
        // 将最后一个元素设为空
        this.elements[index] = null;
        // 长度减一
        this.length--;
        return (T) t;
    }

    @Override
    public int indexOf(T x) {
        // 默认值,查找失败返回-1
        int result = -1;
        for (int i = 0; i < this.length; i++) {
            // 如果查找成功,则返回当前元素下标
            if (this.elements[i] == x) {
                result = i;
                break;
            }
        }
        return result;
    }

    @Override
    public void display() {
        System.out.print("[");
        for (int i = 0; i < this.length; i++) {
            if (i == 0) {
                System.out.print(this.elements[i]);
            } else {
                System.out.print(",");
                System.out.print(this.elements[i]);
            }
        }
        System.out.println("]");
    }

}